#include <iostream>
#include <algorithm>
#include <string>
#include <cstdio>
#include <vector>
#include <stack>
#include <queue>
#include <set>
using namespace std;
struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
    int sum = 0;
    void dfs(TreeNode *root)
    {
        if (root == NULL)
            return;
        dfs(root->right);
        root->val += sum;
        sum = root->val;
        dfs(root->left);
    }
    TreeNode *convertBST(TreeNode *root)
    {
        dfs(root);
        return root;
    }
};